package org.origin.centre.security.authorize;

import org.origin.centre.security.user.XUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;

/**
 * 自定义权限验证
 *
 * @author ferret
 * @version 2024-05-08
 */
@Service("auth")
public class AuthorizeService {

    public boolean hasAnyAuthority(String... authorities) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return false;
        }
        Object principal = authentication.getPrincipal();
        if (principal == null) {
            return false;
        }
        if (principal instanceof XUser) {
            return ((XUser) principal).hasAnyAuthority(authorities);
        }

        Collection<? extends GrantedAuthority> authorityList = authentication.getAuthorities();
        return authorityList.stream()
                .map(GrantedAuthority::getAuthority)
                .filter(StringUtils::hasText)
                .anyMatch(x -> PatternMatchUtils.simpleMatch(authorities, x));
    }
}
